﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Resources;
using AvalonWizard;

namespace Automator.Runtime.Wizards
{
    /// <summary>
    /// Interaction logic for DbWizard.xaml
    /// </summary>
    public partial class DbWizard : Window
    {
        private SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
        public SqlConnectionStringBuilder Result
        {
            get { return (String.IsNullOrEmpty(sb.DataSource)) ? null : sb; }
        }
        
        public Visibility CreateSchemaVisibility
        {
            get { return btnCreateSchema.Visibility; }
            set { btnCreateSchema.Visibility = value; }
        }
        
        public DbWizard()
        {
            InitializeComponent();
            
            wizard.Cancelled += delegate { this.DialogResult = false; Close(); };
            wizard.Finished += delegate { this.DialogResult = true; Close(); };
            wizard.CurrentPageChanged += new EventHandler<CurrentPageChangedEventArgs>(wizard_CurrentPageChanged);
            DbRadioButton_Click(null, new RoutedEventArgs());
        }
        
        public DbWizard(SqlConnectionStringBuilder value): this()
        {
            if (value != null)
            {
                edtDbServer.Text = value.DataSource;
                edtDbCatalog.Text = value.InitialCatalog;
                rbDbWindows.IsChecked = value.IntegratedSecurity;
                rbDbSqlServer.IsChecked = !value.IntegratedSecurity;
                edtDbLogin.Text = value.UserID;
                edtDbPassword.Password = value.Password;                
                DbRadioButton_Click(null, new RoutedEventArgs());
            }
        }

        private void wizard_CurrentPageChanged(object sender, CurrentPageChangedEventArgs e)
        {
            e.Handled = true;
            if (e.NewPage.Name.Equals("pgSummary"))
            {
                sb.ApplicationName = "Automator";
                sb.DataSource = edtDbServer.Text;
                sb.InitialCatalog = edtDbCatalog.Text;
                sb.IntegratedSecurity = rbDbWindows.IsChecked.Value;
                sb.UserID = edtDbLogin.Text;
                sb.Password = edtDbPassword.Password;
                if (!String.IsNullOrEmpty(sb.DataSource))
                    edtConnString.Text = sb.ConnectionString;
            }
        }
        
        private void DbRadioButton_Click(object sender, RoutedEventArgs e)
        {
            edtDbLogin.IsEnabled = rbDbSqlServer.IsChecked.Value;
            edtDbPassword.IsEnabled = rbDbSqlServer.IsChecked.Value;
        }
        
        private void BtnTestConnection_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(sb.DataSource))
            {
                using (SqlConnection conn = new SqlConnection(Result.ConnectionString))
                {
                    try
                    {
                        conn.Open();
                        Microsoft.Windows.Controls.MessageBox.Show(this, "Test successful", "Connection", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch (Exception ex)
                    {
                        Microsoft.Windows.Controls.MessageBox.Show(this, ex.Message, "Connection", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
        
        private void BtnCreateSchema_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(sb.DataSource))
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(Result.ConnectionString))
                    {
                        conn.Open();
                        using (SqlCommand command = new SqlCommand())
                        {
                            command.Connection = conn;
                            Uri uri = new Uri("/Automator.Runtime;component/Resources/schema.sql", UriKind.Relative);
                            StreamResourceInfo info = Application.GetResourceStream(uri);
                            info.Stream.Position = 0;
                            using (TextReader reader = new StreamReader(info.Stream))
                            {
                                command.CommandText = reader.ReadToEnd();
                            }
                            command.ExecuteNonQuery();
                            Microsoft.Windows.Controls.MessageBox.Show(this, "Schema created", "Connection", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Microsoft.Windows.Controls.MessageBox.Show(this, ex.Message, "Connection", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    }
}